package com.qf.studentmanager.service;

import com.qf.studentmanager.config.DBConfig;
import com.qf.studentmanager.dao.GradeDao;
import com.qf.studentmanager.model.Grade;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GradeService {
    GradeDao gradeDao = new GradeDao();



    public Integer addGrade(String gradeName, String[] cids) {
        Grade grade = gradeDao.getGradeByGradeName(gradeName);
        if (grade != null){
            return -2; //重复了。
        }else {
            Connection connection = DBConfig.getConnection();
            try {
                connection.setAutoCommit(false);
                Grade grade1 = new Grade();
                grade1.setGradeName(gradeName);
                Integer r1 = gradeDao.addGrade(grade1); //运行了这条语句里面的方法后，grade就有了gid。下面就可以用gid和上传来的cids【】去添加关联表了

//                int i1 = 1 / 0;
                Integer[] cs = new Integer[cids.length];
                for (int i = 0; i < cids.length; i++) {
                    cs[i] = Integer.parseInt(cids[i]);
                }

                Integer r2 = gradeDao.addGradeAndCourse(grade1.getGid(), cs);
                connection.commit();
                return (r1 == 1 && r2 == cids.length) ? 1 : -1;
            } catch (SQLException e) {
                e.printStackTrace();
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }


        }
        return -1;
    }

    public List<Grade> getAllGrade() {

        return gradeDao.getAllGrade();
    }

    public Integer deleteGradeByGid(int gid) {
        Connection connection = DBConfig.getConnection();
        try {
            connection.setAutoCommit(false);
            Integer integer = gradeDao.deleteGradeByGid(gid);
            gradeDao.deleteGradeAndCourse(gid);
            connection.commit();
            return integer;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return -1;
    }
}
